<template>
  <el-container>
    <!-- <RegionTree style="margin-top: 16px" @on-choose-region="filetrRegion" /> -->
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="[
            'refresh',
            'add',
            'edit',
            'upload',
            'export',
            'remove',
            'comSearch',
            'columnDisplay',
          ]"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 表单 -->
        <PopupForm ref="formRef" v-if="baTable.form.operate" />
        <!-- 初始化到活性炭监控表单 -->
        <Origin />
        <!-- 上传文件 -->
        <Upload
          v-if="baTable.form.operate && baTable.form.operate === 'upload'"
        />
      </div>
    </el-main>
  </el-container>
</template>
<script setup lang="ts">
import {
  ref,
  provide,
  onMounted,
  markRaw,
  onBeforeUnmount,
  reactive,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { DeviceMAccess } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useAccess } from "@/store/backend/DeviceM/access";
import PopupForm from "./popupForm.vue";
import Origin from "./components/origin.vue";
import Upload from "./components/import.vue";
import { useRouter, useRoute, onBeforeRouteUpdate } from "vue-router";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor"; //实时设备监控仓库
import _ from "lodash";
import TagState from "@/components/dictTagState/index.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import { useCarbon } from "@/store/backend/EquipM/activeCarbon";
import TagSearch from "@/components/tagSearch/index.vue";
import { useNavTabs } from "@/store/navTabs";
import { useModel } from "@/store/backend/DeviceM/model";

var timer: NodeJS.Timer;

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const access = useAccess();
const carbon = useCarbon();
const router = useRouter();
const route = useRoute();
const monitor = useBackendMonitor();
const dictionary = useDictionary();
const navTabs = useNavTabs();
const model = useModel();

const formRef = ref();
//全局事件总线
const { proxy } = useCurrentInstance();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 字段显隐记忆功能 字段中有默认隐藏false情况的
const filedShowOffDefault = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(route.path + "/" + filter)
      ? true
      : false;
  }
  return "";
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + DeviceMAccess)
      ? (navTabs as any).pageSizeMap.get(route.path + DeviceMAccess)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(DeviceMAccess), //this.api = api菜单管理相关
  {
    pk: "id", //设备id
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("equipmentCode"),
        label: "设备编号",
        prop: "equipmentCode",
        align: "center",
        operatorPlaceholder: "精确搜索",
      },
      {
        show: filedShowOff("equipmentName"),
        label: "设备名称",
        prop: "equipmentName",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("gatewaycode"),
        label: "网关编号",
        prop: "gatewaycode",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("state"),
        label: "设备状态",
        prop: "state",
        align: "center",
        width: "90",
        render: "customRender",
        customRender: markRaw(TagState),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("equipmentType"),
        label: "设备类型",
        prop: "equipmentType",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("code"),
        label: "车间代码",
        prop: "code",
        align: "left",
      },
      {
        show: filedShowOff("name"),
        label: "车间名称",
        prop: "name",
        align: "left",
      },
      // {
      //   show: filedShowOff("estate"),
      //   label: "运行状态",
      //   prop: "estate",
      //   align: "center",
      //   width: "90",
      //   render: "tag",
      //   custom: { 1: "success", 0: "warning", 2: "danger" },
      //   replaceValue: {
      //     1: "正常",
      //     0: "异常",
      //     2: "告警",
      //   },
      // },
      // {
      //   show:
      //     filedShowOffDefault("openState") === ""
      //       ? false //默认false
      //       : filedShowOffDefault("openState"),
      //   label: "设备启停",
      //   prop: "openState",
      //   align: "center",
      //   width: "80",
      //   render: "switchAccess",
      //   replaceValue: {
      //     0: "停",
      //     1: "启",
      //   },
      //   operator: false,
      // },
      // {
      //   // show: access.switch,
      //   show: false,
      //   label: "设备启停",
      //   prop: "openState",
      //   align: "center",
      //   width: "90",
      //   render: "tag",
      //   custom: { 0: "danger", 1: "success" },
      //   replaceValue: {
      //     0: "停",
      //     1: "启",
      //   },
      //   operator: false,
      // },
      // { label: "信号强度", prop: "signal", align: "center", operator: false },
      // {
      //   show: filedShowOff("production"),
      //   label: "生产设备运行状态",
      //   prop: "production",
      //   align: "center",
      //   width: "90",
      //   render: "tag",
      //   custom: { 0: "info", 1: "success", 2: "info" },
      //   replaceValue: {
      //     0: "未运行",
      //     1: "运行",
      //     2: "未知",
      //   },
      // },
      {
        show: operatorShowOff([
          route.path + "/edit",
          route.path + "/add",
          route.path + "/remove",
        ]),
        label: "操作",
        align: "center",
        width: "170",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          // {
          //   render: "tipButton",
          //   name: "origin",
          //   title: "活性炭监控初始化",
          //   text: "",
          //   type: "primary",
          //   icon: "fa fa-retweet",
          //   class: "table-row-edit",
          //   disabledTip: false,
          // },
          {
            render: "tipButton",
            name: "accessInfo",
            title: "详情",
            text: "",
            type: "primary",
            icon: "iconfont icon-chaxunyujisuan",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: {
      // regions: [region.regionIds] + "",
      // institution: access.companyid ? access.companyid : "" + "",
      // cname: route.query.cname,
      // estate: route.query.estate,
      // state: route.query.state,
      // openState: route.query.openState,
      pageSize: pageSizeKeep(),
    },
    acceptQuery: false,
  },
  {
    defaultItems: { state: 2, openState: 0 },
  },
  // 操作前置方法列表，返回false则取消原操作
  {},
  // 操作后置方法列表，先执行表格本身的查看、删除、编辑、双击、等，再执行本处添加的后置操作
  {}
);
// const List = () => {
//   /**
//    * 如果所属企业列表数据为空 不使用tabel类默认getList方法来获取数据
//    *  使用List()方法保证在处理完企业列表之后或者所属企业列表数据为空的情况下获取数据
//    */
//   access
//     .getAccessList({
//       pageNum: 1,
//       pageSize: 10,
//       regions: region.regionIds + "",
//       institution: access.companyid ? access.companyid : "" + "",
//     })
//     .then((res: any) => {
//       baTable.table.data = res.rows;
//       baTable.table.total = res.total;
//       baTable.table.loading = false;
//     });
// };
//打开初始化表单
// const originButtonClick = (name: string, row: anyObj) => {
//   //打开初始化表单
//   baTable.form.operate = name;
//   let temp = { ecode: row.code, eid: row.id };
//   access.item = row;
//   let obj = _.cloneDeep(row);
//   obj.state = 1; //改为离线数据
//   access.item = obj;
//   console.log("access.item", access.item);
//   baTable.form.items = Object.assign(baTable.form.items, temp);
// };
//跳转详情页
const infoButtonClick = (id: number, row: any) => {
  console.log("id", id, "row", row);
  getCarbonDetail(id);
  access.$patch((state) => {
    state.single = row;
  });
  // router.push({ path: "/admin/DeviceM/accessDetail", query: { eid: row.id } });
};
const getCarbonDetail = (id: any) => {
  carbon.getCarbonInfo({ eid: id }).then((res: any) => {
    console.log("跳转详情页", res);
  });
};
// interface Region {
//   address: string | null;
//   addressDetail: string | null;
//   areaFlag: string | null;
//   areaId: number;
//   areaName: string | null;
//   areaNo: string | null;
//   children: Region[];
//   createBy: string | null;
//   createTime: string | null;
//   endTime: string | null;
//   params: any;
//   parentId: number;
//   searchValue: string | null;
//   startTime: string | null;
//   updateBy: string | null;
//   updateTime: string | null;
// }
//接收区域树传递过来的数据
// const filetrRegion = (row: Region, node: any) => {
//   if (node.checkedKeys.length == 0) {
//     //表示取消选择直接调用刷新表单方法
//     baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
//       regions: region.regionIds + "",
//     });
//     baTable.onTableHeaderAction("refresh", {});
//   } else {
//     baTable.comSearch.form.regions = node.checkedKeys + "";
//     baTable.getList(DeviceMAccess);
//   }
// };
onBeforeRouteUpdate((to, form, next) => {
  console.log("当前路由啊,", route);
  next(false);
});

// 双击跳转实况
// proxy.eventBus.on("toMonitor", (row: any) => {
//   console.log("双击", row);
//   //从后台获取该设备数据跳转详情页
//   if (row.state !== 2) {
//     monitor
//       .getnowList({ eid: row.gatewaycode })
//       .then((res) => {
//         console.log("从后台获取该设备数据跳转详情页", res);
//         access
//           .getDeviceByGateway(row.code, region.regionIds)
//           .then((res: any) => {
//             console.log("双击！！！！！！", res);
//             //处理coordinate坐标系
//             res.rows[0].coordinate = JSON.parse(res.rows[0].coordinate);
//             monitor.deviceData = res.rows[0];
//             //为基本信息处理所属企业Map数据格式问题
//             const business = useBusiness();
//             const { companyList } = business;
//             if (companyList.length === 0) {
//               //为空就重新获取企业列表数据
//               business.getCompanyList();
//             }
//           });
//       })
//       .catch((err) => {
//         console.log(err);
//       });
//     router.push({
//       path: "/admin/EquipM/Monitordetail",
//       query: { eid: row.gatewaycode }, //实况详情内事件需要eid
//     });
//   } else {
//     ElNotification({
//       type: "warning",
//       message: "当前设备未激活",
//     });
//   }
// });

//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("device_online_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

onMounted(() => {
  console.log("access.switch!!!!", access.switch);

  proxy.eventBus.emit("pointer"); //el-table显示双击小手套
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  //延后查询 等待查询的前置操作
  baTable.getList(DeviceMAccess);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //用户点击初始化给活性炭监控
      if (data.name == "origin") {
      } else if (data.name == "accessInfo") {
        //详情页面
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
  proxy.eventBus.emit("clear");
});
onBeforeUnmount(() => {
  console.log("触发onBeforeUnmount");
  clearTimeout(timer);
  proxy.eventBus.emit("clear");
  proxy.eventBus.off("toMonitor");
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("model", model);
provide("dictionary", dictionary);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
